


import CommonModal from '@/components/CommonModal';
import Typography from '@/views/components/Typography';
import CommonLoading from '@/components/CommonLoading';
import SubTitle from '@/views/components/SubTitle';
import ShopIcons from '@/views/components/ShopIcons';
import CommonTable from '@/components/CommonTable';
import { useEffect, useMemo, useState } from 'react';
import { Alert, Space, Tag, Button, message } from 'antd';
import { countOrderSum, isManyStore } from '../../config/CheckConfig';
import { agreeExchange, getAfterSalesAddressList, syncAfterSalesAddress } from '../../services';
import { find } from 'lodash';

/** 同意补发/换货 */
function AgreeExchange(props) {
	const { item, selectKeys, tableList, handleOk, handleCancel } = props;
	const { scene } = item;
	const [isOk, setIsOk] = useState(false);
	const [loading, setLoading] = useState(false);
	const [addressList, setAddressList] = useState([]);
	const [selectAddress, setSelectAddress] = useState();
	const [open, setOpen] = useState(false);

	const salesInfo = useMemo(() => {
		return find(tableList, ['id', selectKeys[0]]);
	}, [selectKeys[0]])

	const columns = [
		{
			title: '联系人',
			dataIndex: 'recieverName',
		},
		{
			title: '电话号码',
			dataIndex: 'mobile',
			render: (t, r) => {
				return t || r.tel;
			}
		},
		{
			title: '详细地址',
			dataIndex: 'address',
			render: (t, r) => {
				return `${r.receiverProvinc} ${r.receiverCity} ${r.receiverDistrict} ${r.receiverStreet} ${r.receiverDetail}`
			}
		},
	];

	useEffect(() => {
		setOpen(true);
		getAddressList();
	}, [])

	//初始化信息
	const getAddressList = async () => {
		setLoading(true);
		const { success, data } = await getAfterSalesAddressList({ storeId: salesInfo.ecStoreId });
		if (success && data.length > 0) {
			setAddressList(data);
			setSelectAddress([data[0].id]);
		}
		setLoading(false);
	}

	//同步地址
	const handleSyncAddress = async (storeId) => {
		setLoading(true);
		const { success } = await syncAfterSalesAddress({ storeId });
		if (!success) {
			setLoading(false);
			return;
		}
		const res = await getAfterSalesAddressList({ storeId });
		setLoading(false);
		if (res.success) {
			if (res.data.length > 0) {
				setAddressList(res.data);
				//同步之后如果没有当前选择的地址数据，则重新勾选第一个
				const index = findIndex(res.data, ['id', selectAddress]);
				if (index == -1) {
					setSelectAddress([res.data[0].id]);
				}
			}
			message.info('同步成功！');
		}
	}

	const onOk = async () => {
		if (!selectAddress[0]) {
			message.info('请选择退货地址');
			return;
		}
		setLoading(true);
		const senderAddressInfo = find(addressList, ['id', selectAddress[0]]);
		const { success } = await agreeExchange({
			ids: selectKeys,
			senderAddressInfo: {
				receiverAddressId: senderAddressInfo.addressId
			}
		})
		setLoading(false);
		if (success) {
			message.success('操作成功');
			setIsOk(true);
			setOpen(false);
		}
	}

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		if (isOk) {
			handleOk()
		} else {
			handleCancel();
		}
	}

	//判断是否是单个店铺的，如果不是需要提醒
	if (isManyStore(selectKeys, tableList)) {
		return (
			<CommonModal title="同意补发/换货" afterClose={afterClose} open={open} width="552px" onCancel={onCancel} footer={<Button onClick={onCancel}>关闭</Button>}>
				<div style={{ color: '#333', fontSize: '14px', marginTop: '16px' }}>
					<div>
						请重新勾选，同意补发 / 换货，每次只能处理一个网店店铺
					</div>
					<div>
						并且需要符合以下要求
					</div>
					<div style={{ margin: '12px 0'}}>补发</div>
					<div>换货</div>
				</div>
				<CommonLoading loading={loading} />
			</CommonModal>
		)
	}

	//顶部提示信息
	const tipsContent = (
		<div>
			<div>1、确认即系统自动生成换货、补发订单</div>
			<div>2、同意补寄后，需要在48小时内要审核并生成换货、补寄的物流单号</div>
			<div>（实际具体限制时间以各平台网店要求为准）</div>
		</div>
	)

	//当前满足条件数量
	const countNum = countOrderSum(scene, selectKeys, tableList);

	const TableProps = {
		columns,
		data: addressList,
		rowKey: 'id',
		rowSelection: {
			type: 'radio',
			selectedRowKeys: selectAddress,
			onChange: (selectKeys) => {
				setSelectAddress(selectKeys);
			},
		}
	}

	return (
		<CommonModal title="同意补发/换货" afterClose={afterClose} open={open} width="752px" onOk={onOk} onCancel={onCancel}>
			<Alert showIcon type="info" message={tipsContent} />
			<div style={{ color: '#333', fontSize: '14px', margin: '16px 0' }}>
				<div>
					同意补发/换货，只限操作以下二种状态的售后单：
				</div>
				<div style={{ margin: '12px 0' }}>
					补发：<Typography type="error">{countNum[0]}</Typography>
				</div>
				<div>
					换货：<Typography type="error">{countNum[1]}</Typography>
				</div>
				<Space style={{ marginTop: '12px' }}><ShopIcons type={salesInfo.orderChannel} />{salesInfo.ecStoreName}</Space>
				<SubTitle wrapStyle={{ margin: '12px 0' }} symbol as="s2" title="选择退货地址" suffix={<Button onClick={() => handleSyncAddress(salesInfo.ecStoreId)} type="link">同步三方平台退货地址</Button>} />
				<CommonTable {...TableProps} />
			</div>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default AgreeExchange;

